<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>组件通信-双向绑定小案例(watch监听实现)</title>
  <style>
    #app {
      text-align: center;
    }

    input {
      margin: 50px 0;
      padding: 4px 0;
      text-align: center;
      border: 1px solid transparent;
      border-bottom: 1px solid steelblue;
      outline: none;
      font-size: 18px;
    }
  </style>
</head>

<body>

  <!-- 父组件模板 -->
  <div id="app">
    <cpn :number1="num1" :number2="num2" @num1change="num1Change" @num2change="num2Change" />
  </div>

  <!-- 子组件模板 -->
  <template id="cpn">
    <div>
      <input type="number" v-model.number="dNum1">
      <h3>父组件: {{ number1 }}</h3>
      <h3>子组件: {{ dNum1 }}</h3>
      <input type="number" v-model.number="dNum2">
      <h3>父组件: {{ number2 }}</h3>
      <h3>子组件: {{ dNum2 }}</h3>
    </div>
  </template>

  <script src="../../js/vue.js"></script>
  <script>
    // 创建子组件
    const cpn = {
      template: '#cpn',
      props: {
        number1: Number,
        number2: Number
      },

      data() {
        return {
          // 根据父组件传递的参数初始化变量
          dNum1: this.number1,
          dNum2: this.number2
        }
      },

      // 监听变量或者计算属性，改变时就会触发
      watch: {
        dNum1(newValue) {
          newValue = newValue || 0;
          console.log("dNum1改变值", newValue);
          this.dNum2 = newValue * 100;
          this.$emit("num1change", newValue);
        },

        dNum2(newValue) {
          newValue = newValue || 0;
          console.log("dNum2改变值", newValue);
          this.dNum1 = newValue / 100;
          this.$emit("num2change", newValue);
        }
      }
    }

    // 父组件，内部注册子组件
    const app = new Vue({
      el: '#app',
      data: {
        num1: 1,
        num2: 2
      },

      components: {
        cpn
      },

      methods: {
        num1Change(value) {
          console.log("子组件传递类型为", typeof value);
          this.num1 = parseFloat(value);
        },

        num2Change(value) {
          this.num2 = parseFloat(value);
        }
      }
    })
  </script>
</body>

</html>